// Mutex 互斥
// Lock() UnLock()
package main

import (
	"fmt"
	"strings"
	"sync"
	"time"
)

var mutex sync.Mutex
var tickets int = 8

func main() {
	var wg sync.WaitGroup
	wg.Add(4)
	go saleTickets(1, "1号窗口", &wg)
	go saleTickets(2, "2号窗口", &wg)
	go saleTickets(3, "3号窗口", &wg)
	go saleTickets(4, "4号窗口", &wg)

	wg.Wait()
	fmt.Println("main end")
}

func saleTickets(num int, name string, wg *sync.WaitGroup) {
	defer wg.Done()
	for {
		mutex.Lock()
		if tickets > 0 {
			time.Sleep(1 * time.Second)
			pre := strings.Repeat("\t", num-1)
			fmt.Println(pre, name, tickets)
			tickets--
		} else {
			fmt.Println(name, "结束售票")
			mutex.Unlock()
			break
		}
		mutex.Unlock()
	}
}
